<?php
App::uses('AppController', 'Controller');
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
/**
 * Orders Controller
 *
 * @property Order $Order
 */
class OrdersController extends AppController {

/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->Order->recursive = 0;
		//$this->Order->order = 'Order.status ASC ,Order.created DESC';
		$orders = $this->Order->find('all', array(	'conditions' => array('Order.archive' => '0'),
													'order' => array('Order.status', 'Order.created DESC')));
		$this->set(compact('orders'));

	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->Order->exists($id)) {
			throw new NotFoundException(__('Invalid order'));
		}
		$order = $this->Order->findById($id);
		
		//print_r($order);

		$this->loadModel('Productsbrands');
		$this->loadModel('Productsranges');
		$this->loadModel('Productscategories');
		$this->loadModel('Gifts');


		foreach($order['Product'] as $i=>$j){
			$brand = $this->Productsbrands->findById($j['productsbrands_id']);
			$order = Set::insert($order, 'Product.'.$i.'.Brand', $brand['Productsbrands']);

			$range = $this->Productsranges->findById($j['productsranges_id']);
			if(empty($range)){$range = array('Productsranges' => array('name' => ''));}
			$order = Set::insert($order, 'Product.'.$i.'.Range', $range['Productsranges']);

			$category = $this->Productscategories->findById($j['productscategories_id']);
			if(empty($category)){$category = array('Productscategories' => array('name' => ''));}
			$order = Set::insert($order, 'Product.'.$i.'.Category', $category['Productscategories']);
		}

		$a = 0;
		foreach($order['Delivery'] as $i=>$j){
			$gift = $this->Gifts->findByDeliveriesId($j['id']);
			if(!empty($gift)){
				$product = $this->Order->Product->findById($gift['Gifts']['products_id']);
				$gift = Set::insert($gift, 'Gifts.Products', $product['Product']);

				$brand = $this->Productsbrands->findById($product['Product']['productsbrands_id']);
				$gift = Set::insert($gift, 'Gifts.Brand', $brand['Productsbrands']);

				$range = $this->Productsranges->findById($product['Product']['productsranges_id']);
				if(empty($range)){$range = array('Productsranges' => array('name' => ''));}
				$gift = Set::insert($gift, 'Gifts.Range', $range['Productsranges']);

				$category = $this->Productscategories->findById($product['Product']['productscategories_id']);
				if(empty($category)){$category = array('Productscategories' => array('name' => ''));}
				$gift = Set::insert($gift, 'Gifts.Category', $category['Productscategories']);

				$order = Set::insert($order, 'Gifts.'.$a, $gift['Gifts']);
				$a++;
			}
		}

		$this->set(compact('order'));
		
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->Order->create();
			if ($this->Order->save($this->request->data)) {
				$this->Session->setFlash(__('The new order has been saved'),'default', array('class' => 'savesuccess'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The order could not be saved. Please try again. '),'default', array('class' => 'saveerror'));
			}
		}
		$suppliers = $this->Order->Suppliers->find('list');
		$this->set(compact('suppliers'));
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->Order->exists($id)) {
			throw new NotFoundException(__('Invalid order'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->Order->save($this->request->data)) {
				$this->Session->setFlash(__('The order has been saved'),'default', array('class' => 'savesuccess'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The order could not be saved. Please try again. '),'default', array('class' => 'saveerror'));
			}
		} else {
			$options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
			$this->request->data = $this->Order->find('first', $options);
		}
		$suppliers = $this->Order->Suppliers->find('list');
		$this->set(compact('suppliers'));
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @throws MethodNotAllowedException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->Order->id = $id;
		if (!$this->Order->exists()) {
			throw new NotFoundException(__('Invalid order'));
		}
		$this->request->onlyAllow('post', 'delete');
		$data = array('id' => $id, 'archive' => '1');
		if ($this->Order->save($data)) {

			//archive delivery
			$delivery = $this->Order->Delivery->find('list', array('conditions'=>array('orders_id'=>$id)));
			foreach ($delivery as $j) {
				$data = array('id' => $j, 'archive' => '1');
				$this->Order->Delivery->save($data);
			}

			//archive ordersproduct
			$this->loadModel('Ordersproduct');
			$this->loadModel('Deliveriesordersproduct');
			$op = $this->Ordersproduct->find('list', array('conditions'=>array('orders_id'=>$id)));
			foreach ($op as $j) {

				//archive deliveriesordersproduct
				$dop = $this->Deliveriesordersproduct->find('list', array('conditions'=>array('ordersproducts_id'=>$j)));
				foreach ($dop as $k) {
					$data = array('id' => $k, 'archive' => '1');
					$this->Deliveriesordersproduct->save($data);
				}

				$data = array('id' => $j, 'archive' => '1');
				$this->Ordersproduct->save($data);
			}

			$this->Session->setFlash(__('The order has been deleted'),'default', array('class' => 'savesuccess'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('The order was not deleted.'),'default', array('class' => 'saveerror'));
		$this->redirect(array('action' => 'index'));
	}

/**
 * choosesupplier method
 *
 * @return void
 */
	public function choosesupplier() {
		if ($this->request->is('post')) {
			$this->redirect(array('action' => 'generate', $this->data['Order']['suppliers_id']));
		}
		$supplier = $this->Order->Suppliers->find('all', array('conditions' => array('archive' => '0')));
		$suppliers = array();
		foreach($supplier as $i=>$j){
			$suppliers = Set::insert($suppliers, $j['Suppliers']['id'], $j['Suppliers']['supplierName']);
		}
		//print_r($suppliers);
		$this->Set(compact('suppliers'));
	}

/**
 * generate method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function generate($id = null) {
		if ($this->request->is('post')) {
			//print_r($this->data);

			//check if there is any order quantity
			$empty = false;
			foreach($this->data['Order'] as $i => $j):
				if(!empty($this->data['Order Quantity'][$i])){
					$empty = true;
				}
			endforeach;

			
			if(!$empty){
				$this->Session->setFlash(__('Order was not created because there was no order quantity.'),'default', array('class' => 'saveerror'));
				$this->redirect(array('action' => 'index'));
			}
			else{
				//print_r($this->request->data);
				$validate = true;
				foreach($this->data['Order Quantity'] as $i => $j){
					if(!empty($j)){
						$data = array('Order Quantity' => $j);
						$this->Order->set($data);

						if ($this->Order->validates()) {
						} else {
						    $validate = false;
						}
					}
				}

				$errors = $this->Order->invalidFields();
				//print_r($errors);

				if(!$validate){
					$this->Session->setFlash(__('Please enter only positive numbers for order quantity.'),'default', array('class' => 'saveerror'));
				}
				else {
					//create new order
					$this->Order->create();
					$data = array('suppliers_id' => $id, 'status' => '0');
					$this->Order->save($data);
					$orderid = $this->Order->id;

					//save each orderproduct
					foreach($this->data['Order'] as $i => $j):
						if(!empty($this->data['Order Quantity'][$i])){
							$data = array(	'products_id' 		=> $j,
											'orders_id'			=> $orderid,
											'orderQty'			=> $this->data['Order Quantity'][$i],
											'deliveredQuantity'	=> '0');
							$this->loadModel('Ordersproducts');
							$this->Ordersproducts->create();
							if($this->Ordersproducts->save($data)){
								
							}
						}
					endforeach;

					$this->Session->setFlash(__('New order has been created'),'default', array('class' => 'savesuccess'));
					$this->redirect(array('action' => 'index'));
				}
			}

		}
		$suppliers = $this->Order->Suppliers->findById($id);
		$this->set(compact('suppliers'));
		//print_r($suppliers);

		$products = $this->Order->Product->find('all', array('conditions'=>array('suppliers_id' => $id, 'archive' => '0')));
		if(empty($products)){
			$this->Session->setFlash(__('There is no products under this supplier.'),'default', array('class' => 'saveerror'));
			$this->redirect(array('action' => 'index'));
		}
		else{
			$this->loadModel('Productsbrands');
			$this->loadModel('Productsranges');
			$this->loadModel('Productscategories');

			$db = $this->Productsbrands->findByName('Salon Accessory');

			$products = $this->Order->Product->find('all', array('conditions'=>array(	'suppliers_id' => $id,
																						'onhand_level <= min_level',
																						'archive' => '0',
																						'productsbrands_id != '.$db['Productsbrands']['id'])));
			//$this->set(compact('products'));

			foreach ($products as $i => $j) {
				
				$brand = $this->Productsbrands->findById($j['Product']['productsbrands_id']);
				$products = Set::insert($products, $i.'.Brands', $brand['Productsbrands']);
				
				$ranges = $this->Productsranges->findById($j['Product']['productsranges_id']);
				if(empty($ranges)){$ranges = array('Productsranges' => array('name' => ''));}
				$products = Set::insert($products, $i.'.Ranges', $ranges['Productsranges']);
				
				$categories = $this->Productscategories->findById($j['Product']['productscategories_id']);
				if(empty($categories)){$categories = array('Productscategories' => array('name' => ''));}
				$products = Set::insert($products, $i.'.Categories', $categories['Productscategories']);
			}

			if(!empty($products)){
				$this->set(compact('products'));
			} else {
				$this->Session->setFlash(__('There is no products under mininum level for this supplier.'),'default', array('class' => 'saveerror'));
				$this->redirect(array('action' => 'index'));
			}
		}
	}

/**
 * viewPdf method
 *
 * @throws NotFoundException
 * @throws MethodNotAllowedException
 * @param string $id
 * @return void
 */
	public function viewPdf($id = null) {
		$this->loadModel('Ordersproduct');
		$this->loadModel('Productsbrands');
		$this->loadModel('Productsranges');
		$this->loadModel('Productscategories');
		$this->loadModel('Suppliers');	
		$this->loadModel('Lukas');

		$conditions = array('conditions' => array('orders_id' => $id));
		$orderproduct = $this->Ordersproduct->find('all', $conditions);
		//print_r($orderproduct);

		foreach ($orderproduct as $i => $j) {
			
			$brand = $this->Productsbrands->findById($j['Products']['productsbrands_id']);
			$orderproduct = Set::insert($orderproduct, $i.'.Brands', $brand['Productsbrands']);
			
			if(!empty($j['Products']['productsranges_id'])){
				$ranges = $this->Productsranges->findById($j['Products']['productsranges_id']);
			}
			else { $ranges = array('Productsranges' => array('name'=> '')); }
			$orderproduct = Set::insert($orderproduct, $i.'.Ranges', $ranges['Productsranges']);
			
			if(!empty($j['Products']['productscategories_id'])){
				$categories = $this->Productscategories->findById($j['Products']['productscategories_id']);
			}
			else { $categories = array('Productscategories' => array('name'=> '')); }
			$orderproduct = Set::insert($orderproduct, $i.'.Categories', $categories['Productscategories']);

			$supplier = $this->Suppliers->findById($j['Orders']['suppliers_id']);
			$orderproduct = Set::insert($orderproduct, $i.'.Suppliers', $supplier['Suppliers']);
		}
		$luka = $this->Lukas->findById('1');
		//print_r($orderproduct);

		$this->set(compact('orderproduct', 'luka'));
		$this->layout = 'pdf'; //this will use the pdf.ctp layout 
		$this->render();
	}

/**
 * editqty method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function editqty($id = null) {
		$this->loadModel('Ordersproducts');
		$ordersproduct = $this->Ordersproducts->findById($id);

		if ($this->request->is('post') || $this->request->is('put')) {
			$data = $this->request->data['Ordersproduct'];
			
			if ($this->Ordersproducts->save($data)) {
				$this->checkorder($ordersproduct['Ordersproducts']['orders_id']);
				$this->Session->setFlash(__('The product quantity has been saved'),'default', array('class' => 'savesuccess'));
				$this->redirect(array('action' => 'view', $ordersproduct['Ordersproducts']['orders_id']));
			} else {
				$this->Session->setFlash(__('The product quantity could not be saved. Please try again. '),'default', array('class' => 'saveerror'));
			}
		}

		$product = $this->Order->Product->findById($ordersproduct['Ordersproducts']['products_id']);
		$ordersproduct = Set::insert($ordersproduct, 'Product', $product['Product']);
		
		$this->set(compact('ordersproduct'));
	}

/**
 * remove method
 *
 * @throws NotFoundException
 * @throws MethodNotAllowedException
 * @param string $id
 * @return void
 */
	public function remove($id = null) {
		$this->loadModel('Ordersproducts');
		$this->loadModel('Deliveriesordersproducts');

		$this->Ordersproducts->id = $id;
		$ordersproduct = $this->Ordersproducts->findById($id);

		if (!$this->Ordersproducts->exists()) {
			throw new NotFoundException(__('Invalid product'));
		}
		$this->request->onlyAllow('post', 'delete');

		$dop = $this->Deliveriesordersproducts->find('all', array('conditions' => array('ordersproducts_id' => $id)));
		if(!empty($dop)){
			$this->Deliveriesordersproducts->id = $dop['0']['Deliveriesordersproducts']['id'];
			if ($this->Deliveriesordersproducts->delete()){
			}
			else{
				$this->Session->setFlash(__('The product could not be deleted.'),'default', array('class' => 'saveerror'));
				$this->redirect(array('action' => 'view', $ordersproduct['Ordersproducts']['orders_id']));
			}
		}
		if ($this->Ordersproducts->delete()) {
			$this->checkorder($ordersproduct['Ordersproducts']['orders_id']);
			$this->Session->setFlash(__('The product has been deleted'),'default', array('class' => 'savesuccess'));
			$this->redirect(array('action' => 'view', $ordersproduct['Ordersproducts']['orders_id']));
		}
		$this->Session->setFlash(__('The product could not be deleted.'),'default', array('class' => 'saveerror'));
		$this->redirect(array('action' => 'view', $ordersproduct['Ordersproducts']['orders_id']));
	}

/**
 * checkorder method
 *
 * @return void
 */
	public function checkorder($id = null) {
		$this->loadModel('Ordersproducts');

		$order = $this->Order->findById($id);
		$ordersproducts = $this->Ordersproducts->find('all', array('conditions'=>array('orders_id' => $id))); 

		$status = '1';
		if($order['Order']['status'] == '0'){
			$status = '2';
		} else if($order['Order']['status'] == '2'){
			foreach ($ordersproducts as $i => $j){
				if($j['Ordersproducts']['orderQty'] != $j['Ordersproducts']['deliveredQty']){
					$status = '2';
				}
			}
		}
		
		$data = array('id' => $id, 'status' => $status);
		$this->Order->save($data);
	}

/**
 * addaccessory method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function addaccessory($id = null) {

		$order = $this->Order->findById($id);
		$supid = $order['Order']['suppliers_id'];
		$suppliers = $this->Order->Suppliers->findById($supid);

		if ($this->request->is('post')) {
			//print_r($this->data);

			//check if there is any order quantity
			$empty = false;
			foreach($this->data['Order'] as $i => $j):
				if(!empty($this->data['Order Quantity'][$i])){
					$empty = true;
				}
			endforeach;

			
			if(!$empty){
				$this->Session->setFlash(__('Order was not saved because there was no order quantity.'),'default', array('class' => 'saveerror'));
				$this->redirect(array('action' => 'view', $id));
			}
			else{
				//print_r($this->request->data);
				$validate = true;
				foreach($this->data['Order Quantity'] as $i => $j){
					if(!empty($j)){
						$data = array('Order Quantity' => $j);
						$this->Order->set($data);

						if ($this->Order->validates()) {
						} else {
						    $validate = false;
						}
					}
				}

				$errors = $this->Order->invalidFields();
				//print_r($errors);

				if(!$validate){
					$this->Session->setFlash(__('Please enter only positive numbers for order quantity.'),'default', array('class' => 'saveerror'));
				}
				else {
					$flag = true;
					//save each orderproduct
					foreach($this->data['Order'] as $i => $j):
						if(!empty($this->data['Order Quantity'][$i])){
							$data = array(	'products_id' 		=> $j,
											'orders_id'			=> $id,
											'orderQty'			=> $this->data['Order Quantity'][$i],
											'deliveredQuantity'	=> '0');
							$this->loadModel('Ordersproducts');
							$this->Ordersproducts->create();
							if($this->Ordersproducts->save($data)){
								
							}
						}
					endforeach;

					if($order['Order']['status'] == '0'){
						$this->Session->setFlash(__('Order has been saved'),'default', array('class' => 'savesuccess'));
						$this->redirect(array('action' => 'view', $id));
					}
					else {
						$data = array('id' => $id, 'status' => '0');
						if($this->Order->save($data)){
							$this->Session->setFlash(__('Order has been saved'),'default', array('class' => 'savesuccess'));
							$this->redirect(array('action' => 'view', $id));
						} else {
							$this->Session->setFlash(__('Order could not be saved properly. Please try again.'),'default', array('class' => 'savesuccess'));
							$this->redirect(array('action' => 'view', $id));
						}
					}
				}
			}

		}
		$this->loadModel('Productsbrands');
		$this->loadModel('Productsranges');
		$this->loadModel('Productscategories');

		$b = $this->Productsbrands->findByName('Salon Accessory');

		$products = $this->Order->Product->find('all', array('conditions'=>array('suppliers_id' => $supid, 'archive' => '0', 'productsbrands_id' => $b['Productsbrands']['id'])));
		if(empty($products)){
			$this->Session->setFlash(__('There is no salon accessory products under this supplier.'),'default', array('class' => 'saveerror'));
			$this->redirect(array('action' => 'view', $id));
		}
		else{
			foreach ($products as $i => $j) {
				
				$products = Set::insert($products, $i.'.Brands', $b['Productsbrands']);
				
				$ranges = $this->Productsranges->findById($j['Product']['productsranges_id']);
				if(empty($ranges)){$ranges = array('Productsranges' => array('name' => ''));}
				$products = Set::insert($products, $i.'.Ranges', $ranges['Productsranges']);
				
				$categories = $this->Productscategories->findById($j['Product']['productscategories_id']);
				if(empty($categories)){$categories = array('Productscategories' => array('name' => ''));}
				$products = Set::insert($products, $i.'.Categories', $categories['Productscategories']);
			}

			$this->set(compact('products', 'suppliers'));
		}
	}
}
